from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet

from goods.models import Goods, Brand, GoodsCategory, GoodsSpecification, SpecificationOption
from meiduo_admin.serializers.goods import SPUSerializer, BrandsSimpleSerializer, ChannelCategoriesSerializer, \
    SPUSpecsSerializer, SpecsOptionsSerializer, GoodsSpecsSimpleSerializer, GoodsBrandsSerializer
from meiduo_admin.utils import PageNum


class SPUModelViewSet(ModelViewSet):
    """查询获取SPU表列表数据"""
    serializer_class = SPUSerializer
    # 分页类
    pagination_class = PageNum

    def get_queryset(self):
        # 提取keyword
        keyword = self.request.query_params.get('keyword')

        if keyword == '' or keyword is None:
            return Goods.objects.all().order_by('id')

        else:
            return Goods.objects.filter(name__contains=keyword).order_by('id')


# 获取品牌信息
class BrandsSimpleView(ListAPIView):
    serializer_class = BrandsSimpleSerializer

    def get_queryset(self):
        queryset = Brand.objects.all()
        return queryset


# 获取一级分类信息
class ChannelCategoriesView(ListAPIView):
    serializer_class = ChannelCategoriesSerializer

    def get_queryset(self):
        pk = self.kwargs.get('pk', None)
        if not pk:
            return GoodsCategory.objects.filter(parent_id=None)
        return GoodsCategory.objects.filter(parent_id=pk)


# 获取规格表列表数据
class SPUSpecsModelViewSet(ModelViewSet):
    serializer_class = SPUSpecsSerializer
    pagination_class = PageNum

    def get_queryset(self):
        pk = self.kwargs.get('pk', None)
        if not pk:
            return GoodsSpecification.objects.all().order_by('id')
        return GoodsSpecification.objects.filter(id=pk).order_by('id')


# 规格选项表管理
class SpecsOptionsModelViewSet(ModelViewSet):
    serializer_class = SpecsOptionsSerializer
    pagination_class = PageNum

    def get_queryset(self):
        pk = self.kwargs.get('pk', None)
        if not pk:
            return SpecificationOption.objects.all().order_by('id')
        return SpecificationOption.objects.filter(id=pk).order_by('id')


# 获取商品规格选项
class GoodsSpecsSimpleView(ListAPIView):
    serializer_class = GoodsSpecsSimpleSerializer
    queryset = GoodsSpecification.objects.all()


# 品牌表管理
class GoodsBrandsModelViewSet(ModelViewSet):
    serializer_class = GoodsBrandsSerializer
    pagination_class = PageNum

    def get_queryset(self):
        pk = self.kwargs.get('pk', None)
        if not pk:
            return Brand.objects.all().order_by('id')
        return Brand.objects.filter(id=pk).order_by('id')
